#include "hal_wdg.h"
#include "hk32c030xx_iwdg.h"

static void iwdg_init(uint32_t timeout) {
	
	if(RCC_GetFlagStatus(RCC_FLAG_IWDGRST) != RESET) {
		RCC_ClearFlag();
	}
	
//    IWDG_Enable();
//    IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
//    IWDG_SetPrescaler(IWDG_Prescaler_32);

//		
//	float cnt = 40.0f / 32 * timeout;
//	uint16_t reload_ = (uint16_t)(cnt + 0.5f);
//    IWDG_SetReload(reload_);

//	while (IWDG_GetFlagStatus(IWDG_FLAG_RVU) != RESET)
//    {
//    }

//	IWDG_SetWindowValue(1000);

	IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);

	//40000 / 32 = 1250
	IWDG_SetPrescaler(IWDG_Prescaler_32);
	
	float cnt = 40.0f / 32 * timeout;
	uint16_t reload_ = (uint16_t)(cnt + 0.5f);
	
	IWDG_SetReload(reload_);
	IWDG_ReloadCounter();
    IWDG_Enable();
}

static void iwdg_reload() {
	
	IWDG_ReloadCounter();
}

const watch_dog_t g_wdg_ = {
    iwdg_init,
    iwdg_reload
};